package cn.lu.train.util;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

public class FragmentFM {

    private int mContainer;
    private FragmentManager mFm;
    private Fragment[] mFragments;

    public FragmentFM(FragmentManager fm, Fragment[] fragments, int container) {
        if (fm == null) {
            throw new IllegalArgumentException("FragmentManager can't be null");
        }
        if (fragments == null) {
            throw new IllegalArgumentException("the fragment array can't be null");
        }
        mFm = fm;
        mFragments = fragments;
        mContainer = container;
    }

    public void show(int index) {
        if (index < mFragments.length) {
            show(mFragments[index]);
        }
    }

    public void show(Fragment target) {
        if (target != null) {
            for (Fragment fragment : mFragments) {
                if (target != fragment) {
                    hidden(fragment);
                }
            }
            if (!target.isAdded()) {
                mFm.beginTransaction().add(mContainer, target).show(target).commit();
            } else {
                if (!target.isVisible()) {
                    mFm.beginTransaction().show(target).commit();
                }
            }
        }
    }

    public void hidden(int index) {
        if (index < mFragments.length) {
            hidden(mFragments[index]);
        }
    }

    public void hidden(Fragment fragment) {
        if (fragment != null && fragment.isAdded() && !fragment.isHidden()) {
            mFm.beginTransaction().hide(fragment).commit();
        }
    }

    public void remove(int index) {
        if (index < mFragments.length) {
            removeFragment(mFragments[index]);
        }
    }

    public void removeAll() {
        for (Fragment mFragment : mFragments) {
            removeFragment(mFragment);
        }
    }

    private void removeFragment(Fragment fragment) {
        if (fragment != null && fragment.isAdded()) {
            mFm.beginTransaction().remove(fragment).commitAllowingStateLoss();
        }
    }

    public Fragment getFragment(int index) {
        if (index < mFragments.length) {
            return mFragments[index];
        }
        return null;
    }

    public Fragment[] getFragments() {
        return mFragments;
    }
}
